package com.generic;

import org.junit.jupiter.api.Test;

import java.util.*;

/**
 * @author LingLed
 * @version 1.0
 * P566
 */
public class Homework01 {
    public static void main(String[] args) {
        DAO<User> userDAO = new DAO<>();
        userDAO.save("1",new User(1,20,"张三"));
        userDAO.save("2",new User(2,20,"李四"));
        userDAO.save("3",new User(3,20,"王五"));
        userDAO.save("4",new User(4,20,"赵六"));
        //updateValue
        System.out.println(userDAO.update("1",new User(1,20,"张三丰")));
        //getValue
        System.out.println(userDAO.get("1"));
        //deleteValue
        System.out.println(userDAO.delete("1"));
        //list<User>
        List<User> users = userDAO.list();

    }
}

class DAO<T>{
    Map<String,T> map;
    {
        map = new HashMap<>();
    }
    @Test
    public boolean save(String id,T entity){
        //保存对象
        //id作为key，T对象作为value
        return map.put(id, entity) == null;
    }
    public T get(String id){
        //从map获取
        //根据id获取T对象
        return map.get(id);
    }
    public boolean update(String id,T entity){
        //更新map中的对象
        //根据id更新T对象
        if(map.containsKey(id)){
            map.put(id,entity);
            return true;
        }
        return false;
    }
    public boolean delete(String id){
        //删除map中的对象
        //根据id删除T对象
        return map.remove(id) != null;
    }
    public List<T> list(){
        List<T> l1 = new ArrayList<>();
        l1.addAll(map.values());
        //返回map中存放的所有T对象
        return l1;
    }
}

class User{
    private int id;
    private int age;
    private String name;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public User(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id && age == user.age && Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, age, name);
    }
}